import { message, Upload, Button, Form, Select, Space } from 'antd';
import { DeleteOutlined, FileOutlined, FolderOutlined } from '@ant-design/icons';
import type { GetProp, UploadProps, UploadFile } from 'antd';
import UserSearch from '@/components/UserSearch';
import { useState } from 'react';
import styles from './index.module.less'
import { STATUS_CODE } from '@/common/const'
type FileType = Parameters<GetProp<UploadProps, 'beforeUpload'>>[0];

type FieldType = {
    patientnumber?: string;
    ks?: string;
    sz?: string;
};
type IProps = {
    id: string | null;
    uploadApi: (data: FormData) => Promise<any>;
    type?: 'tjjg' | 'rjzp'
}
const FileAdd = (props: IProps) => {
    const { id, uploadApi, type } = props;
    const [fileList, setFileList] = useState<UploadFile[]>([]);
    const [uploading, setUploading] = useState(false);
    const uploadProps: UploadProps = {
        style: {
            margin: '40px 0'
        },
        name: 'file',
        beforeUpload(file, newFileList) {
            setFileList([...fileList, ...newFileList]);
            return false;
        },
        showUploadList: false
    };
    const deleteFile = (index) => {
        const newFileList = [...fileList]
        newFileList.splice(index, 1);
        setFileList(newFileList);
    }
    const fileProps: UploadProps = {
        ...uploadProps,
        multiple: true,

    }
    const directoryProps: UploadProps = {
        ...uploadProps,
        directory: true,
    }

    const startUpload = async () => {
        console.log(fileList)
        const formData = new FormData();
        formData.append('recordId', id);
        type && formData.append('classify', type);
        fileList.forEach((file) => {
            formData.append('files', file as FileType);
        });
        setUploading(true);
        try {
            const res = await uploadApi(formData)
            if (res.code === STATUS_CODE.SUCCESS) {
                message.success('上传成功');
                setFileList([])
            }
        } catch (error) {
            message.error('上传失败，请少量多次上传');
        } finally {
            setUploading(false);
        }
    }
    return (
        <>
            <Space align='center' >
                <Upload {...fileProps} >
                    <Button icon={<FileOutlined />}>选择文件</Button>
                </Upload>

                <Upload {...directoryProps}>
                    <Button icon={<FolderOutlined />}>选择文件夹</Button>
                </Upload>
            </Space>
            {
                fileList.length > 0 ? <div className={styles.uploadList}>
                    {fileList.map((item, index) => {
                        return <div key={item.uid} className={styles.fileRow}>
                            <div className={styles.fileName}>{item.name}</div>
                            <div className={styles.delete} onClick={() => deleteFile(index)}><DeleteOutlined /></div>
                        </div>
                    }
                    )}
                </div> : null
            }
            {fileList.length > 0 ? <Button type='primary' className={styles.uploadBtn} onClick={startUpload} loading={uploading}>开始上传</Button> : null}
        </>

    )
}

const CreateRecord = ({ onFinish, api, type }) => {
    const [submitLoading, setSubmitLoading] = useState(false)
    const handleFinish = async (values: FieldType) => {
        const result = await api({ ...values, type })
        if (result.code === STATUS_CODE.SUCCESS) {
            message.success('添加成功!')
            onFinish()
        } else {
            message.error(result.message)
        }
        setSubmitLoading(false)
    }
    return (
        <Form
            name="basic"
            labelCol={{ span: 8 }}
            style={{ maxWidth: 600 }}
            onFinish={handleFinish}
            autoComplete="off"
        >
            <Form.Item<FieldType>
                label="姓名/胸牌号"
                name="patientnumber"
                rules={[{ required: true }]}
            >
                <UserSearch />
            </Form.Item>

            <Form.Item<FieldType>
                label="科室"
                name="ks"
                rules={[{ required: true }]}
            >
                <Select
                    options={[
                        { value: '内科', label: '内科' },
                        { value: '外科', label: '外科' },
                        { value: '传染病', label: '传染病' },
                    ]}
                />
            </Form.Item>

            <Form.Item dependencies={['ks']}
            >
                {({ getFieldValue }) => {
                    const ks = getFieldValue('ks')
                    return ks === '外科' ? (
                        <Form.Item
                            label="伤种"
                            name="sz"
                            labelCol={{ span: 8 }}
                        >
                            <Select
                                options={[
                                    { value: '工伤', label: '工伤' },
                                    { value: '他伤', label: '他伤' },
                                    { value: '意外伤', label: '意外伤' },
                                ]} />
                        </Form.Item>) : null
                }}
            </Form.Item>

            <Form.Item wrapperCol={{ offset: 8, span: 16 }}>
                <Button type="primary" htmlType="submit" onClick={() => setSubmitLoading(true)} loading={submitLoading}>
                    提交
                </Button>
            </Form.Item>
        </Form>)
}
export {
    FileAdd,
    CreateRecord
} 